﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Illisian.Utils.IO;

namespace L2Sharp.Net.Packets.Login
{
    public abstract class BaseSendablePacket
    {
        
        ByteArrayOutputStream _bao;

        protected BaseSendablePacket()
        {
            _bao = new ByteArrayOutputStream();
        }

        protected void writeD(int Value)
        {
            _bao.Write(System.Net.IPAddress.HostToNetworkOrder(Value));
        }

        protected void writeC(int Value)
        {
            _bao.Write(System.Net.IPAddress.HostToNetworkOrder(Value));
        }

        /// <summary>
        /// Write a String out to the Byte Stream
        /// </summary>
        /// <param name="text">Text to Write Out</param>
        protected void writeS(string text)
        {
            try
            {
                if (text != null)
                {
                    _bao.Write(System.Text.ASCIIEncoding.Unicode.GetBytes(text));
                }
            }
            catch
            { }

            _bao.Write(0);
            _bao.Write(0);

        }

        /// <summary>
        /// Writes a byte array to the byte stream
        /// </summary>
        /// <param name="array"></param>
        protected void writeB(byte[] array)
        {
            try
            {
                _bao.Write(array);
            }
            catch (Exception e)
            {
            }
        }


        public int getLength()
        {
            return _bao.Size() + 2;
        }

        public byte[] getBytes()
        {
            writeD(0);
            int padding = _bao.Size();
            if (padding != 0)
            {
                for (int i = padding; i < 8; i++)
                {
                    writeC(0);
                }
            }

            return _bao.ToByteArray();
        }

        public abstract byte[] getContent();

    }
}
